package com.tq68.weixin.controller.login;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MessageApi;
import com.jfinal.weixin.sdk.api.QrcodeApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.tq68.weixin.model.Seller;

public class AdminiController extends ApiController{

	public void index(){
		render("index.html");
	}
	//群发信息by openid
	public void sendMsg(){
		/**
		 * 构造json
		 * 	获取openid列表
		 *  获取要发送的内容：有图片的话要先上传
		 */
		String msgContent = getPara("msgContent");
		String[] openids = new String[]{"obscJsxSGZWj3N4IDf0vr11s7LQ8","obscJs1b1acovy57xCFb1SQ5UMIg","obscJswjoxgTYb4ScvSQq-BWju9I"};
		StringBuffer jsonStr = new StringBuffer();
		jsonStr.append("{");
		jsonStr.append("	   \"touser\":[");
		jsonStr.append("	    \""+openids[0]+"\",");
		jsonStr.append("	    \""+openids[1]+"\",");
		jsonStr.append("	    \""+openids[2]+"\"");
		jsonStr.append("	   ],");
		jsonStr.append("\"msgtype\": \"text\",");
		jsonStr.append("\"text\": { \"content\": \""+msgContent+"\"}");
		jsonStr.append("	}");
		MessageApi.send(jsonStr.toString());
		renderText("OK");
	}
	//群发前预览
	public void sendMsgPreview(){
		String msgContent = getPara("msgContent");
		String openid = "obscJs1b1acovy57xCFb1SQ5UMIg";
		StringBuffer jsonStr = new StringBuffer();
		jsonStr.append("{");
		jsonStr.append("    \"touser\":\""+openid+"\",");
		jsonStr.append("    \"text\":{");
		jsonStr.append("           \"content\":\""+msgContent+"\"");           
		jsonStr.append("           },");
		jsonStr.append("    \"msgtype\":\"text\"");
		jsonStr.append("}");
		MessageApi.preview(jsonStr.toString());
		renderText("OK");
	}
	//根据商家账号（字符串长度为1-64）生成商家永久型二维码图片
	public void getScanCodeForSeller(){
		Integer sellerid = getParaToInt("sellerid",0);
		Seller seller = Seller.dao.findById(sellerid);
		if(seller!=null){
			String ticket = "";
			if(StringUtils.isBlank(seller.getScanCode())){
				ApiResult result = QrcodeApi.createPermanent(seller.getSellerAccount());
				ticket = result.getStr("ticket");
				seller.setScanCode(ticket);
				seller.update();
			}else{
				ticket = seller.getScanCode();
			}
			//根据二维码ticket获取图片显示地址
			String picUrl = QrcodeApi.getShowQrcodeUrl(ticket);
			renderText(picUrl);
		}else{
			renderText("ERROR");
		}
	}
	
	@Override
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));
		
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}
}
